<template>
  <el-form :model="userInfo" :rules="rules" ref="formRef" label-width="100px">
    <!-- 第一行：登录名称 -->
    <el-form-item label="登录名称" prop="username">
      <el-input v-model="userInfo.username" disabled></el-input>
    </el-form-item>

    <!-- 第二行：用户昵称 -->
    <el-form-item label="用户昵称" prop="nickname">
      <el-input v-model="userInfo.nickname"></el-input>
    </el-form-item>

    <!-- 第三行：用户邮箱 -->
    <el-form-item label="用户邮箱" prop="email">
      <el-input v-model="userInfo.email"></el-input>
    </el-form-item>

    <!-- 第四行：提交按钮 -->
    <el-form-item>
      <el-button type="primary" @click="submitForm">提交修改</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { userUpdateInfoService } from '@/api/user';
import { useUserStore } from '@/stores/user.js'

const userStore = useUserStore()

const {
  user: { username, nickname, email, id }
} = useUserStore()

const userInfo = ref({ username, nickname, email, id })

// 校验规则
const rules = ref({
  nickname: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ]
});

// 表单引用
const formRef = ref(null);

// 提交表单的方法
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      await userUpdateInfoService(userInfo.value)
      await userStore.getUser()
      ElMessage.success('修改成功')

      // 这里可以添加实际的提交逻辑，例如调用API等
    } else {
      console.log('error submit!!');
      return false;
    }
  });
};
</script>

<style scoped>
/* 可选：为表单添加样式 */
.el-input {
  width: 300px;
}
</style>
